import axios from "axios";
import qs from "qs";

const env = process.env.NODE_ENV;
const base = process.env.VUE_APP_BASE_URL;

console.log(env, base);

const http = axios.create({
  baseURL: base,
  timeout: 5000,
  transformRequest: [
    function(data) {
      return qs.stringify(data);
    }
  ]
});

// 请求拦截
http.interceptors.request.use(
  config => {
    // token 登录验证
    if (localStorage.getItem("Authorization")) {
      config.headers.Authorization = localStorage.getItem("Authorization");
    }
    // 设置 请求头      对象合并
    config.headers = Object.assign(
      config.method.toLocaleLowerCase() === "get"
        ? {
            Accept: "application/json",
            "Content-Type": "application/json; charset=UTF-8"
          }
        : {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
          },
      config.headers
    );
    if (
      config.method.toLocaleLowerCase() === "post" ||
      config.method.toLocaleLowerCase() === "put"
    ) {
      // 参数统一处理，请求都使用data传参
      config.data = config.data.data;
    } else if (
      config.method.toLocaleLowerCase() === "get" ||
      config.method.toLocaleLowerCase() === "delete"
    ) {
      // 参数统一处理
      config.params = config.data;
    } else {
      alert("不允许的请求方法：" + config.method);
    }
    console.log(config);
    return Promise.resolve(config);
  },
  err => {
    return Promise.reject(err);
  }
);
// 响应拦截
http.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return Promise.resolve(response.data);
    }
  },
  err => {
    return Promise.reject(err);
  }
);

export default http;
